package com.hncic.tx.center.mvc.util;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hncic.tx.center.common.util.Constant;
import com.hncic.tx.center.common.util.UtilJson;
import com.hncic.tx.center.common.vo.JsonData0;

public class HttpAuthorizeFilter implements Filter{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) arg0;

		boolean present = Optional.ofNullable(httpRequest.getSession(false))
				.map(v -> v.getAttribute(Constant.TxSessKey)).isPresent();
		if (!present) {
			logger.warn("HttpAuthorizeAttribute not present path:{}", arg0.getLocalAddr());
			JsonData0 res = new JsonData0(403);
			res.setMsg("author error");

			arg1.setCharacterEncoding("UTF-8");
			arg1.setContentType("application/json; charset=UTF-8");
			arg1.getWriter().write(UtilJson.writeValueAsString(res));
			// throw new TxBussException(403, "author error");
			return;
		}
		chain.doFilter(arg0, arg1);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
}